import logging
import os
import urllib
import wsgiref.handlers

from django.utils import simplejson
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

webapp.template.register_template_library('templatefilters')

class MainPage(webapp.RequestHandler):
	template_path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
	def get(self):
		user = users.get_current_user()
		if user:
			url = users.CreateLogoutURL('/')
		else:
			url = users.CreateLoginURL(self.request.uri)
		template_values = {
			'url':	url,
			'user':	user,
		}
		self.response.out.write(template.render(MainPage.template_path, template_values))
		
class SearchPage(webapp.RequestHandler):
    template_path = os.path.join(os.path.dirname(__file__), 'templates/search.html')
    def get(self):
        query = unicode.encode(self.request.get('q'),"utf-8")
        start = self.request.get('start')
        if not start:
            start = '0'

        # **************** PUT YOUR APP_ID
        url = "http://boss.yahooapis.com/ysearch/web/v1/" + urllib.quote(query) + "?start=" + start + "&appid=your_app_id"
        response = urlfetch.fetch(url=url, headers={'Content-Type': 'application/json'})

        results = []

        # **************** REMOVE "True: #" AFTER PUT YOUR APP_ID IN THE PREVIOUS LINE
        if True: #response.status_code == 200:
            # sample query response
            results = simplejson.loads('{"ysearchresponse":{"responsecode":"200","nextpage":"/ysearch/web/v1/demo?appid=00000&start=10","totalhits":"25329502","deephits":"746000000","count":"10","start":"0","resultset_web":[{"abstract":"Offers men\'s and women\'s clothing, shoes, and accessories.","clickurl":"http://www.demostores.com/","date":"2008/07/17","dispurl":"www.<b>demostores.com</b>","size":"33578","title":"<b>demo</b>","url":"http://www.demostores.com/"},{"abstract":"Showcase for emerging technologies and companies. Includes registration information, video archives, and a blog.","clickurl":"http://www.demo.com/","date":"2008/07/15","dispurl":"www.<b>demo.com</b>","size":"62466","title":"<b>Demo</b> Conference","url":"http://www.demo.com/"},{"abstract":"<b>Demo</b> downloads, reviews, screenshots, and cheats.","clickurl":"http://www.gamedemo.com/","date":"2008/07/16","dispurl":"www.<b>gamedemo.com</b>","size":"168887","title":"GameDemo.com","url":"http://www.gamedemo.com/"},{"abstract":"Offers a variety of downloads, free game demos, summaries, and more.","clickurl":"http://www.pcgameworld.com/downloads/type.php/dltype/1/","date":"2008/07/17","dispurl":"www.<b>pcgameworld.com</b>/downloads/<wbr>type.php/dltype/1","size":"38454","title":"Game Demos - PC Gameworld","url":"http://www.pcgameworld.com/downloads/type.php/dltype/1/"},{"abstract":"Joomla! - Content Management System and Web Application Framework <b>...</b> Please report any problems with the <b>demo</b> Web site in the Sites &amp; Infrastructure forum. <b>...</b>","clickurl":"http://demo.joomla.org/","date":"2008/05/13","dispurl":"<b>demo.joomla.org</b>","size":"11095","title":"Joomla! <b>Demo</b>","url":"http://demo.joomla.org/"},{"abstract":"<b>Demo</b> is the work of Justin Fines, an art director and designer living and working in New York City <b>...</b> Design / Art Direction / Broadcast Design. Brooklyn, NY <b>...</b>","clickurl":"http://www.demo-design.com/","date":"2007/12/17","dispurl":"www.<b>demo-design.com</b>","size":"6943","title":"<b>Demo</b>","url":"http://www.demo-design.com/"},{"abstract":"Here you will have the opportunity to preview Citrix products and technologies <b>...</b> Learn more in this <b>demo</b> showcasing Citrix SmartAccess, powered by the Citrix <b>...</b>","clickurl":"http://www.citrix.com/English/ps2/demo.asp","date":"2008/07/08","dispurl":"www.<b>citrix.com</b>/English/ps2/<b>demo</b>.asp","size":"65312","title":"Citrix <b>Demo</b> Center","url":"http://www.citrix.com/English/ps2/demo.asp"},{"abstract":"A <b>demo</b> is a non-interactive multimedia presentation made within the computer <b>...</b> Most <b>demo</b> parties have at least one intro competition, where the rules are <b>...</b>","clickurl":"http://en.wikipedia.org/wiki/Demo_(computer_programming)","date":"2008/07/11","dispurl":"<b>en.wikipedia.org</b>/wiki/<wbr><b>Demo</b>_(computer_programming)","size":"63316","title":"<b>Demo</b> (computer programming) - Wikipedia, the free encyclopedia","url":"http://en.wikipedia.org/wiki/Demo_(computer_programming)"},{"abstract":"<b>Demo</b> (computer programming), a non-interactive multimedia presentation, a type of digital art <b>...</b> <b>DEMO</b>, a proposed experimental nuclear fusion reactor <b>...</b>","clickurl":"http://en.wikipedia.org/wiki/Demo","date":"2008/06/12","dispurl":"<b>en.wikipedia.org</b>/wiki/<b>Demo</b>","size":"19094","title":"<b>Demo</b> - Wikipedia, the free encyclopedia","url":"http://en.wikipedia.org/wiki/Demo"},{"abstract":"Skip to Content Java Solaris Communities About Sun How to Buy. My Sun Connection Cart <b>...</b> You can view the screen shots. Evaluate. Product Home. Promotions. <b>Demo</b>. Use <b>...</b>","clickurl":"http://www.sun.com/software/looking_glass/demo.xml","date":"2008/06/29","dispurl":"www.<b>sun.com</b>/software/looking_glass/<wbr><b>demo</b>.xml","size":"12265","title":"Project Looking Glass - <b>Demo</b>","url":"http://www.sun.com/software/looking_glass/demo.xml"}]}}')

            # real query (only works over app engine servers. not work in local)
            #results = simplejson.loads(response.content)        

        search_results = None
        totalhits = 0
        if results.has_key('ysearchresponse'):
            if results['ysearchresponse'].has_key('resultset_web'):
                search_results = results['ysearchresponse']['resultset_web']
            if results['ysearchresponse'].has_key('totalhits'):
                totalhits = results['ysearchresponse']['totalhits']

        template_values = {
            'first': start,
            'last': int(start) + len(search_results),
            'npage': int(start)/10,
            'query': query,
            'results': search_results,
            'totalhits': totalhits
        }
        self.response.out.write(template.render(SearchPage.template_path, template_values))
	
		
def main():
	logging.getLogger().setLevel(logging.DEBUG)
	application = webapp.WSGIApplication(
										[('/', MainPage),
										('/search.*', SearchPage)],
                                       debug=True)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
